package org.example.foodhealth.service;

import jakarta.persistence.TypedQuery;
import org.example.foodhealth.bean.UserLogin;
import org.example.foodhealth.dto.UserLoginDTO;
import org.example.foodhealth.repository.UserLoginRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserLoginService {
    @Autowired
    private UserLoginRepository userLoginRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 注册用户
    public void registerUser(UserLoginDTO userLoginDTO) {
        // 对密码进行哈希处理
        String password = passwordEncoder.encode(userLoginDTO.getPassword());

        // 创建 UserLogin 实例
        UserLogin user = new UserLogin(userLoginDTO.getEmail(), userLoginDTO.getPhone(), password);

        // 保存用户到数据库
        userLoginRepository.save(user);
    }

    //查找手机号
    public Optional<UserLogin> getUserByPhone(String phone) {
        return userLoginRepository.findByPhone(phone);
    }

    //查找邮箱
    public Optional<UserLogin> getUserByEmail(String email) {
        return userLoginRepository.findByEmail(email);
    }

    //更新用户信息
    public void updateUser(UserLogin user) {
        userLoginRepository.save(user);
    }
}
